import React, { useCallback, useEffect, useRef, useState } from 'react';
import { IFile, ITarget, IWork, IWorkTask, TaskTypeName } from '@/ts/core';
import { command } from '@/ts/base';
import orgCtrl from '@/ts/controller';
import { Spin, Image, Modal, Form as UIForm, Input, Tabs, Badge } from 'antd';
import DirectoryViewer from '@/components/Directory/views';
import { loadFileMenus } from '@/executor/fileOperate';
import { cleanMenus, getUuid } from '@/utils/tools';
import useTimeoutHanlder from '@/hooks/useTimeoutHanlder';
import AppLayout from '@/components/MainLayout/appLayout';
import { useFlagCmdEmitter } from '@/hooks/useCtrlUpdate';
import SelectWork from './select';
import FullScreenModal from '@/components/Common/fullScreen';
import OrgIcons from '@/components/Common/GlobalComps/orgIcons';
import message from '@/utils/message';
import { FormEditData } from '@/ts/base/model';
import './index.less';
import TaskViewer from './TaskViewer';
import { OrderStatus, orderStatusMap } from '@/ts/base/enum';
/**
 * 办事-事项清单
 */
const WorkContent: React.FC = () => {
  const [tab, setTab] = useState<'办事' | '任务' | '订单'>('办事');

  const currentTag = useRef<string>('待办');
  const [loaded, setLoaded] = useState(false);
  const [selectOpen, setSelectOpen] = useState(false);
  const [content, setContent] = useState<IFile[]>([]);
  const [viewContent, setViewContent] = useState<IFile[]>([]);
  const [focusFile, setFocusFile] = useState<IFile>();
  const [submitHanlder, clearHanlder] = useTimeoutHanlder();
  const [todoRefresh, setTodoRefresh] = useState<string>();
  const [autoApproval, setAutoApproval] = useState(false);
  const autoApprovalComment = useRef<string>('自动通过');
  const [center, setCenter] = useState(<></>);
  const [autoName, setAutoName] = useState('-');
  const [pendingOrderCount, setPendingOrderCount] = useState(0);
  const ids: string[] = [];
  const [, key] = useFlagCmdEmitter('_commons', () => {
    if (currentTag.current === '常用') {
      loadContent('常用');
    }
  });
  useEffect(() => {
    setPendingOrderCount(orgCtrl.pendingOrderCount);
    const id = orgCtrl.work.notity.subscribe((...args) => {
      const [_key, tag] = args;
      if (tag === undefined || tag === '待办') {
        if (currentTag.current === '待办') {
          loadContent('待办');
        } else {
          setTodoRefresh(getUuid());
        }
      } else if (tag === '草稿' && currentTag.current === tag) {
        currentTag.current = tag;
        loadContent(tag);
      }
    });

    const orderId = orgCtrl.subscribe((_, type, data) => {
      if (type === 'orderNumber') {
        setPendingOrderCount(data);
      }
    });

    return () => {
      orgCtrl.work.notity.unsubscribe(id);
      orgCtrl.unsubscribe(orderId);
      orgCtrl.work.tiggleAutoApproval(false, autoApprovalComment.current, [], (msg) =>
        message.info(msg),
      );
    };
  }, []);

  useEffect(() => {
    orgCtrl.work.tiggleAutoApproval(
      autoApproval,
      autoApprovalComment.current,
      viewContent as IWorkTask[],
      (msg) => message.info(msg),
    );
  }, [autoApproval, viewContent]);

  useEffect(() => {
    if (['已办', '抄送', '已发起', '已完结'].includes(currentTag.current)) {
      loadContent(currentTag.current);
    }
  }, [autoName]);

  useEffect(() => {
    if (!focusFile) {
      command.emitter('preview', 'guidance', { empty: true, type: currentTag.current });
    }
    command.emitter('preview', 'work', focusFile, currentTag.current);
  }, [focusFile]);

  const contextMenu = (file?: IFile) => {
    return {
      items: cleanMenus(loadFileMenus(file)) || [],
      onClick: ({ key }: { key: string }) => {
        command.emitter('executor', key, file);
      },
    };
  };

  const focusHanlder = (file: IFile | undefined) => {
    if (file && file.key !== focusFile?.key) {
      setFocusFile(file);
    }
  };

  const clickHanlder = (file: IFile | undefined, dblclick: boolean) => {
    if (dblclick && currentTag.current !== '草稿') {
      clearHanlder();
      if (file) {
        command.emitter('executor', 'open', file);
      }
    } else {
      submitHanlder(() => focusHanlder(file), 200);
    }
  };

  const getBadgeCount = useCallback(
    (tag: string) => {
      if (tag === '待办') {
        return orgCtrl.work.todos.length;
      }
      return 0;
    },
    [todoRefresh],
  );

  const loadContent = (tag: string) => {
    if (tag?.length < 2) return;
    if (tag === '常用') {
      loadCommons();
    } else if (tag === '任务') {
      loadReceptions();
    } else if (tag === OrderStatus.PROCESSING || tag === OrderStatus.COMPLETED) {
      loadOrder(tag, []);
    } else if (tag === '重载任务') {
      loadReceptions();
    } else if (tag === '草稿') {
      loadDrafts();
    } else {
      command.emitter('preview', 'guidance', {
        empty: content.length == 0,
        loading: true,
        type: tag,
      });
      loadTasks(tag, []);
    }
  };
  const loadCommons = () => {
    setLoaded(false);
    orgCtrl.loadCommons().then((value) => {
      setLoaded(true);
      const data = value.filter((i) => i.typeName === '办事');
      setContent(data);
    });
  };

  const loadOrder = (tag: string, args: any[]) => {
    setLoaded(false);
    orgCtrl.loadOrder(orderStatusMap[tag], args.length).then((value) => {
      const newOrderItems = [...args, ...(value?.orderItems || [])].sort((a, b) => {
        return new Date(b.updateTime).getTime() - new Date(a.updateTime).getTime();
      });
      setContent(newOrderItems);
      tag === OrderStatus.PROCESSING && setPendingOrderCount(value?.totalCount || 0);
      setLoaded(true);
    });
  };

  const loadDrafts = () => {
    setLoaded(false);
    orgCtrl.work.loadDraft(true).then((value) => {
      setLoaded(true);
      setContent(value);
    });
  };
  const loadTasks = (tag: string, args: IFile[]) => {
    setLoaded(false);
    let reload = false;
    if (tag === '重载待办') {
      tag = '待办';
      reload = true;
    }
    orgCtrl.work
      .loadContent(
        tag as TaskTypeName,
        autoName == '-' ? '' : autoName,
        args.length,
        reload,
      )
      .then((tasks) => {
        tasks.forEach((task) => {
          if (ids.includes(task.taskdata.instanceId)) {
            task.loadExecutors().then(async (executors) => {
              const executor = executors.find(
                (item) =>
                  item.metadata.funcName == '字段变更' ||
                  item.metadata.funcName == '任务状态变更',
              );
              if (!executor || executor.metadata.funcName === '任务状态变更') {
                command.emitter('preview', 'work', undefined);
                if (executor && task.instanceData?.reception) {
                  const formData = new Map<string, FormEditData>();
                  await executor.execute(formData);
                  message.info(task.name + '执行成功！');
                }
              }
            });
          }
        });
        const newTasks = [...args, ...tasks].sort((a, b) => {
          return (
            new Date(b.metadata.updateTime).getTime() -
            new Date(a.metadata.updateTime).getTime()
          );
        });
        setContent([...newTasks]);
        setLoaded(true);
        if (tag == '待办') {
          setTimeout(() => {
            command.emitter('preview', 'guidance', {
              empty: newTasks.length == 0,
              loading: false,
              type: tag,
            });
          }, 10);
        }
      })
      .catch((reason) => {
        message.error(reason);
        setContent([]);
        setLoaded(true);
      });
  };

  const loadReceptions = () => {
    setLoaded(false);
    orgCtrl.loadAssignTasks().then((value) => {
      setContent(value);
      setLoaded(true);
    });
  };

  const renderMore = () => {
    switch (currentTag.current) {
      case '常用':
        return (
          <div className="chat-leftBar-search_more">
            <Image
              preview={false}
              height={24}
              width={24}
              onClick={() => {
                setSelectOpen(true);
              }}
              src={`/svg/operate/todoMore.svg?v=1.0.1`}
            />
          </div>
        );
      case '待办':
        return (
          <>
            <div className="chat-leftBar-search_more">
              <OrgIcons
                type="/operate/reload"
                size={22}
                notAvatar
                title="重载待办"
                onClick={() => loadContent('重载待办')}
              />
            </div>
            {autoName.length > 1 && (
              <div className="chat-leftBar-search_more">
                <OrgIcons
                  type={`/operate/${autoApproval ? 'setActive' : 'active'}`}
                  size={22}
                  notAvatar
                  title={`${autoApproval ? '停止自动审核' : '开启自动审核'}`}
                  onClick={() => {
                    if (autoApproval) {
                      setAutoApproval((pre) => !pre);
                      return;
                    }
                    setCenter(
                      <Modal
                        title="自动审核信息"
                        open={true}
                        onOk={() => {
                          if (!autoApprovalComment.current.trim().length) {
                            message.error('自动审批意见不允许为空！');
                            return;
                          }
                          setCenter(<></>);
                          setAutoApproval((pre) => !pre);
                        }}
                        onCancel={() => setCenter(<></>)}>
                        <UIForm
                          initialValues={{
                            comment: '自动通过',
                          }}
                          autoComplete="off"
                          onValuesChange={(values) => {
                            const { comment } = values;
                            autoApprovalComment.current = comment;
                          }}>
                          <UIForm.Item label="审批意见" name="comment">
                            <Input
                              placeholder="请输入审批意见"
                              style={{ width: '100%' }}
                            />
                          </UIForm.Item>
                        </UIForm>
                      </Modal>,
                    );
                  }}
                />
              </div>
            )}
          </>
        );
      case '任务':
        return (
          <>
            <div className="chat-leftBar-search_more">
              <OrgIcons
                type="/operate/reload"
                size={22}
                notAvatar
                title="重载任务"
                onClick={() => loadContent('重载任务')}
              />
            </div>
            <div className="chat-leftBar-search_more">
              <OrgIcons
                type="/operate/newWork"
                size={22}
                notAvatar
                title="新建任务"
                onClick={() => command.emitter('executor', 'newReportTask', {})}
              />
            </div>
          </>
        );
    }
    return <></>;
  };
  return (
    <AppLayout previewFlag={'work'}>
      <Spin spinning={!loaded} tip={'加载中...'}>
        <div key={key} style={{ marginLeft: 10, fontSize: 18 }}>
          {/* <span style={{ paddingLeft: 10 }}>办事</span> */}
          <Tabs
            className="work-switch-tab"
            activeKey={tab}
            onChange={(key) => {
              setTab(key as any);
              switch (key) {
                case '任务':
                  currentTag.current = '任务';
                  break;
                case '订单':
                  currentTag.current = OrderStatus.PROCESSING;
                  break;
                default:
                  currentTag.current = '待办';
              }
              loadContent(currentTag.current);
            }}
            size="small"
            items={[
              {
                key: '办事',
                label: '办事',
                children: <></>,
              },
              {
                key: '任务',
                label: '任务',
                children: <></>,
              },
              {
                key: '订单',
                label: (
                  <Badge
                    count={pendingOrderCount}
                    size="small"
                    offset={pendingOrderCount > 99 ? [18, 0] : [6, 0]}>
                    <span>订单</span>
                  </Badge>
                ),
                children: <></>,
              },
            ]}
          />
        </div>
        {tab == '办事' && (
          <DirectoryViewer
            isMenu
            extraTags={false}
            currentTag={currentTag.current}
            height={'calc(100% - 120px)'}
            selectFiles={[]}
            focusFile={focusFile}
            content={content}
            badgeCount={getBadgeCount}
            tagChanged={(t) => {
              currentTag.current = t;
              setAutoApproval(false);
              loadContent(t);
            }}
            initTags={['常用', '草稿', '待办', '已办', '抄送', '已发起', '已完结']}
            fileOpen={(entity, dblclick) => clickHanlder(entity as IWorkTask, dblclick)}
            contextMenu={(entity) => contextMenu(entity as IWorkTask)}
            rightBars={renderMore()}
            onScrollEnd={() => {
              if (['已办', '抄送', '已发起', '已完结'].includes(currentTag.current)) {
                loadTasks(currentTag.current, content);
              }
            }}
            onFilter={(filter) => {
              setAutoName(filter);
              setAutoApproval(false);
            }}
            onFocusFile={(file) => {
              setFocusFile(file as IFile);
            }}
            onViewChanged={(files) => setViewContent(files as IFile[])}
          />
        )}
        {tab == '任务' && (
          <TaskViewer
            height="calc(100vh - 72px)"
            openTask={(reception) => {
              clickHanlder(reception, false);
            }}
          />
        )}
        {tab == '订单' && (
          <DirectoryViewer
            isMenu
            extraTags={false}
            currentTag={currentTag.current}
            height={'calc(100% - 120px)'}
            selectFiles={[]}
            focusFile={focusFile}
            content={content}
            badgeCount={getBadgeCount}
            tagChanged={(t) => {
              currentTag.current = t;
              setAutoApproval(false);
              loadContent(t);
            }}
            initTags={[OrderStatus.PROCESSING, OrderStatus.COMPLETED]}
            fileOpen={(entity, dblclick) => clickHanlder(entity as IWorkTask, dblclick)}
            contextMenu={() => ({ items: [], onClick: () => {} })}
            rightBars={renderMore()}
            onScrollEnd={() => {
              if (
                [OrderStatus.PROCESSING, OrderStatus.COMPLETED].includes(
                  currentTag.current as OrderStatus,
                )
              ) {
                loadOrder(currentTag.current, content);
              }
            }}
            onFocusFile={(file) => {
              setFocusFile(file as IFile);
            }}
            onViewChanged={(files) => setViewContent(files as IFile[])}
          />
        )}
        {selectOpen && (
          <FullScreenModal
            open
            title={'选择办事'}
            onCancel={() => {
              setSelectOpen(false);
            }}
            destroyOnClose
            width={1000}
            bodyHeight={'75vh'}>
            <SelectWork
              onSelected={(work: IWork) => {
                setSelectOpen(false);
                setTimeout(() => {
                  setFocusFile(work);
                }, 500);
              }}
            />
          </FullScreenModal>
        )}
      </Spin>
      {center}
    </AppLayout>
  );
};
export default WorkContent;
